from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from app01 import models
from app01.myform import MyRegForm
from django.contrib import auth
from django.contrib.auth.decorators import login_required
# Create your views here.

def register(request):
    form_obj = MyRegForm()
    # form_obj = MyRegForm({'username':'jason','password':'123','confirm_password':'123','email':'1111@13.com'})
    if request.method == 'POST':
        back_dic = {'code':1000, 'msg':''}
        form_obj = MyRegForm(request.POST)
        #判断数据是否合法
        if form_obj.is_valid():
            cleaned_data = form_obj.cleaned_data #只有数据通过验证，才能展示校验通过的数据
            # 将字典里面的confirm_password键值对删除
            cleaned_data.pop('confirm_password') # {'username': 'jason', 'password': '123', 'email': '123@qq.com'}
            file_obj = request.FILES.get('avatar')
            if file_obj:
                cleaned_data['avatar'] = file_obj
            models.UserInfo.objects.create_user(**cleaned_data)
            back_dic['url'] = '/login/'
        else:
            back_dic['code'] = 2000
            back_dic['msg'] = form_obj.errors
        return JsonResponse(back_dic)
    return render(request,'register.html',locals())

def login(request):
    if request.method == 'POST':
        back_dic = {'code':1000,'msg':''}
        username = request.POST.get('username')
        password = request.POST.get('password')
        code = request.POST.get('code')
        print(request.session)
        # 1 先校验验证码是否正确      自己决定是否忽略            统一转大写或者小写再比较
        if request.session.get('code').upper() == code.upper():
            # 2 校验用户名和密码是否正确
            user_obj = auth.authenticate(request,username=username,password=password)
            if user_obj:
                #保存用户状态
                auth.login(request,user_obj)
                back_dic['url'] = '/home/'
            else:
                back_dic['code'] = 2000
                back_dic['msg'] = '用户名或者密码错误'
        else:
            back_dic['code'] = 3000
            back_dic['msg'] = '验证码错误'
        return JsonResponse(back_dic)
    return render(request, 'login.html')

def home(request):
    article_queryset = models.Article.objects.all()
    return render(request,'home.html',locals())

@login_required
def logout(request):
    auth.logout(request)
    return redirect('/home/')

def site(request, username, **kwargs):
    user_obj = models.UserInfo.objects.filter(username=username)
    # 用户如果不存在应该返回一个404页面
    if not user_obj:
        return render(request,'error.html')
    blog = user_obj.blog
    # 查询当前个人站点下的所有的文章




from PIL import Image,ImageDraw,ImageFont
"""
Image:生成图片
ImageDraw:能够在图片上乱涂乱画
ImageFont:控制字体样式
"""
from io import BytesIO,StringIO
"""
内存管理器模块
BytesIO:临时帮你存储数据 返回的时候数据是二进制
StringIO:临时帮你存储数据 返回的时候数据是字符串
"""
import random
def get_random():
    return random.randint(0,255), random.randint(0,255), random.randint(0,255)

def get_code(request):
    # 直接从后端获取数据
    # with open('static/img/111.jpg','rb') as f:
    #     data = f.read()
    # return HttpResponse(data)
    img_obj = Image.new('RGB', (200,35), get_random())
    img_draw = ImageDraw.Draw(img_obj) #产生一个画笔对象
    img_font = ImageFont.truetype('static/font/222.ttf',30) #字体样式，大小
    # 随机验证码  五位数的随机验证码  数字 小写字母 大写字母
    code = ''
    for i in range(5):
        random_upper = chr(random.randint(65,90))
        random_lower = chr(random.randint(97,122))
        random_int = str(random.randint(0,9))
        tmp = random.choice([random_upper,random_int,random_lower])
        # 将产生的随机字符串写入到图片上
        """
        为什么一个个写而不是生成好了之后再写
        因为一个个写能够控制每个字体的间隙 而生成好之后再写的话
        间隙就没法控制了
        """
        img_draw.text((i*40, -2), tmp, get_random(), img_font) # xy坐标，画的对象，画的颜色，画的样式
        code += tmp
    print(code)
    # 随机验证码在登陆的视图函数里面需要用到 要比对 所以要找地方存起来并且其他视图函数也能拿到
    request.session['code'] = code
    io_obj = BytesIO() # 生成一个内存管理器对象  你可以看成是文件句柄
    img_obj.save(io_obj,'png') #保存到内存管理器中
    return HttpResponse(io_obj.getvalue()) #从内存管理器中读取二进制的图片数据返回给前端


